package com.kingtop.base.service.impl;

import com.kingtop.base.dao.IBaseAuthorityDao;
import com.kingtop.base.dao.IBaseRoleAuthorityDao;
import com.kingtop.base.dao.IBaseUserAuthorityDao;
import com.kingtop.base.dao.IBaseUserDao;
import com.kingtop.base.model.BaseAuthority;
import com.kingtop.base.model.BaseRoleAuthority;
import com.kingtop.base.model.BaseUser;
import com.kingtop.base.model.BaseUserAuthority;
import com.kingtop.base.service.IBaseAuthorityService;
import org.kingtop.mybatis.mapper.BaseServiceImpl;
import org.kingtop.mybatis.plugin.Pagination;
import org.kingtop.sys.PageBean;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;


@Service("BaseAuthorityService")
public class BaseAuthorityServiceImpl extends BaseServiceImpl<BaseAuthority> implements IBaseAuthorityService {

	@Resource
	private IBaseAuthorityDao baseAuthorityDao;
	
	@Resource
	private IBaseRoleAuthorityDao baseRoleAuthorityDao;
	
	@Resource
	private IBaseUserAuthorityDao baseUserAuthorityDao;

	@Resource
	private IBaseUserDao baseUserDao;
	
	@SuppressWarnings("unchecked")
	@Override
	public BaseAuthority get(Long id) {
		if(id == null)
			return null;
		return baseAuthorityDao.getById(id);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<BaseAuthority> listAllAuthority() {
		return baseAuthorityDao.listAll();
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<BaseRoleAuthority> listAllRoleAuthority() {
		return this.baseRoleAuthorityDao.getAllRoleAuthority();
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<BaseUserAuthority> listAllUserAuthority() {
		return baseUserAuthorityDao.getAllUserAuthority();
	}

	@Override
	public List<String> listByUsername(String userName) {
		BaseUser baseUser = this.baseUserDao.getByUsername(userName);
		List<BaseAuthority> list = this.baseAuthorityDao.findAuthorityByUserId(baseUser.getId());
		List<String> signs = new ArrayList<>();
		for (BaseAuthority authority : list) {
			signs.add(authority.getAuthoritySign());
		}
		return signs;
	}

	@Override
	public List<String> listAuthorityByRoles(List<String> roleSigns) {
		if(roleSigns == null || roleSigns.size() == 0)
			return Collections.emptyList();
		List<BaseAuthority> list = this.baseAuthorityDao.getPermissionsByRole(roleSigns);
		List<String> signs = new ArrayList<>();
		for (BaseAuthority authority : list) {
			signs.add(authority.getAuthoritySign());
		}
		return signs;
	}

	@Override
	public PageBean<BaseAuthority> pageList(BaseAuthority baseAuthority, int pageIndex, int pageSize) {
		return this.baseAuthorityDao.pageList(baseAuthority, Pagination.of(pageIndex, pageSize));
	}

}